self.addEventListener('install', function(event) {
    console.error('installing');
    event._from = 'callback2'
    console.log('install callback 2: ' + (Date.now()/1000));

    // 测试 install 状态
    event.waitUntil(new Promise(function(resolve) {
        setTimeout(() => {
            console.log('resolve 5s')
            resolve()
        }, 1000);
    }));


    // 测试 redundant
    // var CACHE_NAME = "my_cache";
    // var urlsToCache = [
    //     '/index.html',
    //     '/css/style.css',
    //     '/js/script.js'
    // ];
    // event.waitUntil(
    //     caches.open(CACHE_NAME).then(function(cache) {
    //         console.log('Opendhe : ',cache);
    //         return cache.addAll(urlsToCache);
    //     })
    // );
});
self.addEventListener('activate', function (event) {
    console.error('activate');
    event.waitUntil(new Promise(function(resolve) {
        setTimeout(() => {
            console.log('resolve 5s')
            resolve();
        }, 2000);
    }));
});

self.addEventListener('message', event => { 
    // 直接跳过等待状态，直接接管页面
    console.error('测试message：', event);
    if (event.data === 'skip') {
        self.skipWaiting();
    }
    
    self.clients.matchAll({includeUncontrolled:true}).then(function(clients) {
        console.error('我在里面, 我是异步的');
        let senderId = event.source ? event.source.id : 'unknow'
        clients.forEach(client => {
            if (senderId === client.id) {
                return;
            } else {
                client.postMessage({
                    client: senderId,
                    message: event.data
                });
            }
        })
    })
});

self.addEventListener('fetch', event => {
    // 可以结合cache 做一些缓存处理
    // 自定义返回值
    // 注意特别耗性能，谨慎处理
    // console.error(event.request.url);
    if (new URL(event.request.url).search.includes('intercept')){
        event.respondWith(new Promise(resolve => {
            if (new URL(event.request.url).search.includes('count')) {
                fetch(event.request).then(function(response) {
                    console.error('Response from network is:', response);

                    return resolve(response);
                });
            } else if (new URL(event.request.url).search.includes('intercept')) {
                resolve(new Response('Hello World!'));
            }
        }));

    }
});


self.addEventListener('sync', function (e) {
    if (e.tag == 'dai') {
        e.waitUntil(new Promise(res => {
            fetch('/web.worker.js').then(function (response) {
                console.error(response);
                // doSomething
            })
        }));
    }
});


self.addEventListener('push', function(event) {
    console.error(event.data.text());
    self.registration.showNotification("Hi：", {
        body: '我收到了push',
        icon: 'http://localhost:8080/images/tangcusuan.a548a.png',
        tag: 'push'
    });
});
